<?php


namespace app\admin\controller;


use app\admin\service\RbacService;
use app\common\controller\CommonController;
use app\common\enum\MainEnum;
use app\common\exception\ParameterFailedException;
use app\common\exception\NotFoundException;
use app\common\model\MediaGroupModel;
use app\common\model\MediaModel;
use app\common\model\ProductCategoryModel;
use app\common\model\ProductModel;
use app\common\service\Lang;
use app\common\service\Qiniu;
use app\common\validate\MediaValidate;
use app\common\validate\ProductValidate;
use app\Request;
use PhpOffice\PhpWord\Media;
use think\facade\Db;
use think\facade\Env;

class MediaController extends CommonController
{
    public function uploadFile(Request $request)
    {
        Db::startTrans();
        try {

            //            $params      = self::getParam(['type']);
            //            (new MediaValidate())->goCheck(__FUNCTION__, $params);
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('file');
            if (!$file) {
                throw new ParameterFailedException();
            }
            //                halt($files[0]->getOriginalName());die;
            // 移动到框架应用根目录/uploads/ 目录下
            switch (config('filesystem.default')) {
                //                case 'local':
                //                    $path = config('filesystem.disks.local.root');
                //                    break;
                //                case 'public';
                //                    $path = config('filesystem.disks.public.root');
                //                    break;
                case 'qiniuyun';
                    $path = config('filesystem.disks.qiniuyun.root');
                    break;
                default:
                    throw new ParameterFailedException(['msg' => '只支持七牛云']);
            }
            //            $saveFileInfo = [];
            $temp         = \think\facade\Filesystem::putFile('', $file);
            $filesavepath = $path . DIRECTORY_SEPARATOR . $temp;
            //            $saveFileInfo[] = [
            //                'savename'      => $temp,
            //                'filename'      => $files[0]->getOriginalName(),
            //                'complete_file' => $path . DIRECTORY_SEPARATOR . $temp,
            //            ];
            $filename = getUniqueStr().$file->getOriginalName();
            (new Qiniu())->uploadFile($filesavepath, $filename);

            Db::commit();
            unlink($filesavepath);
            return retJson(Lang::UPLOADDone, ['url' => 'https://file.uziyuan.vip/' . $filename]);
        } catch (\Exception $e) {
            if (isset($filesavepath)) {
                unlink($filesavepath);
            }
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function getMediaGroupList()
    {
        $searchParams = self::getParam([]);
        $where        = [];
        foreach ($searchParams as $key => $value) {
            if (is_array($value) && $key === 'create_time') {
                $where[] = [
                    $key,
                    'between',
                    $value,
                ];
                continue;
            }
            if (strpos($value, '%') !== false) {
                $where[] = [
                    $key,
                    'like',
                    $value,
                ];
            }
            else {
                $where[] = [
                    $key,
                    '=',
                    $value,
                ];
            }
        }
        $where = [];
        $model = (new MediaGroupModel())->with([])->order([
            //            'sea_waybill_number' => 'desc',
            //            'case_number'        => 'desc',
            'create_time' => 'desc',
        ])->where($where)->paginate([
            'page'      => $this->page,
            'list_rows' => $this->limit,
        ]);
        return retJson(Lang::GETDone, $model->toArray());
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \Exception
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/10/20
     * @Time: 14:24
     */
    public function postMediaGroup(): ?\think\response\Json
    {

        $params      = self::getParam([
            'media_group_name',
        ]);
        (new MediaValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $oldModel = (new MediaGroupModel())->where('name', $params['media_group_name'])->find();
            if ($oldModel) {
                throw new ParameterFailedException(['msg' => '已存在该数据']);
            }

            $model       = new MediaGroupModel();
            $model->name = $params['media_group_name'];

            $model->save();

            Db::commit();
            return retJson(Lang::POSTDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function putMediaGroup()
    {

        $params      = self::getParam([
            'media_group_id',
            'media_group_name',
        ]);
        (new MediaValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $model = MediaGroupModel::where('id', $params['media_group_id'])->find();
            if (!$model) {
                throw new NotFoundException();
            }
            //
            //            $mediaModel = MediaModel::where('group_id', $params['media_group_id'])->find();
            //            if ($mediaModel) {
            //                throw new NotFoundException(['msg' => '该数据已被绑定，请解除绑定后继续操作']);
            //            }

            $model->name = $params['media_group_name'];
            $model->save();

            Db::commit();
            return retJson(Lang::PUTDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \Exception
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/10/20
     * @Time: 14:35
     */
    public function deleteMediaGroup(): ?\think\response\Json
    {

        $params      = self::getParam(['media_group_id']);
        (new MediaValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $model = MediaGroupModel::where('id', $params['media_group_id'])->find();
            if (!$model) {
                throw new NotFoundException();
            }

            $mediaModel = MediaModel::where('group_id', $params['media_group_id'])->find();
            if ($mediaModel) {
                throw new NotFoundException(['msg' => '该数据已被绑定，请解除绑定后继续操作']);
            }

            $model->delete_time = NOW_TIME;
            $model->save();

            Db::commit();

            return retJson(Lang::DELETEDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function getMediaList()
    {
        $searchParams = self::getParam([]);
        $where        = [];
        foreach ($searchParams as $key => $value) {
            if (is_array($value) && $key === 'create_time') {
                $where[] = [
                    $key,
                    'between',
                    $value,
                ];
                continue;
            }
            if (strpos($value, '%') !== false) {
                $where[] = [
                    $key,
                    'like',
                    $value,
                ];
            }
            else {
                $where[] = [
                    $key,
                    '=',
                    $value,
                ];
            }
        }
        $where = [];
        $model = (new MediaModel())->with(['groupInfo'])->order([
            //            'sea_waybill_number' => 'desc',
            //            'case_number'        => 'desc',
            'create_time' => 'desc',
        ])->where($where)->paginate([
            'page'      => $this->page,
            'list_rows' => $this->limit,
        ]);
        return retJson(Lang::GETDone, $model->toArray());
    }

    public function postMedia()
    {

        $params      = self::getParam([
            'media_group_id',
        ]);
        (new MediaValidate())->goCheck(__FUNCTION__, $params);

        // 获取表单上传文件 例如上传了001.jpg
        $files = request()->file('files');
        if (count($files) > 20) {
            throw new ParameterFailedException(['msg' => '最大上传的图片数量不能超过20个']);
        }
        //                halt($files[0]->getOriginalName());die;
        // 移动到框架应用根目录/uploads/ 目录下
        switch (config('filesystem.default')) {
            case 'local':
                $path = config('filesystem.disks.local.root');
                break;
            case 'public';
                $path = config('filesystem.disks.public.root');
                break;
            default:
                $path = '';
        }
        $saveFileInfo = [];
        try {
            validate(['image' => 'filesize:1024*1024*10|fileExt:jpg|image:200,200,jpg'])->check($files);
            foreach ($files as $file) {
                $temp           = \think\facade\Filesystem::putFile('', $file);
                $saveFileInfo[] = [
                    'savename'      => $temp,
                    'filename'      => $file->getOriginalName(),
                    'complete_file' => $path . DIRECTORY_SEPARATOR . $temp,
                ];
            }
            $saveArr         = [];
            $md5ConditionArr = [];
            foreach ($saveFileInfo as $item) {
                $saveArr[] = [
                    'group_id'         => $params['media_group_id'],
                    'filename'         => $item['filename'],
                    'type'             => MainEnum::MEDIA_TYPE_IMAGE,
                    'storage_location' => MainEnum::MEDIA_STORAGE_LOCATION_LOCAL,
                    'savename'         => $item['savename'],
                    'encrypted_value'  => $md5ConditionArr[] = md5_file($item['complete_file']),
                ];
            }

            $md5ConditionModels = (new MediaModel())->whereIn('encrypted_value', $md5ConditionArr)->select();
            if (!$md5ConditionModels->isEmpty()) {
                $errorFileUrls = [];
                foreach ($md5ConditionModels as $md5ConditionModel) {
                    foreach ($saveFileInfo as $item) {
                        if (md5_file($item['complete_file']) === $md5ConditionModel->encrypted_value) {
                            $errorFileUrls[] = $md5ConditionModel->getAttr('savename');
                        }
                    }
                }
                throw new ParameterFailedException([
                    'msg'  => '图片已存在',
                    'data' => $errorFileUrls,
                ]);
            }
            $model = new MediaModel();
            $model->saveAll($saveArr);
            Db::commit();
            return retJson(Lang::POSTDone);
        } catch (\Exception $e) {
            Db::rollback();
            foreach ($saveFileInfo as $item) {
                if (is_file($item['complete_file'])) {
                    unlink($item['complete_file']);
                }
            }
            throw $e;
        }
    }

    public function putMedia()
    {

        $params      = self::getParam([
            'id',
            'media',
        ]);
        (new MediaValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $model = MediaModel::where('id', $params['id'])->find();
            if (!$model) {
                throw new NotFoundException();
            }

            //product
            //attr 检测是否有图片使用，有的话不能删除
            //            $carModel = ProdModel::where('driver_id', $params['id'])->find();
            //            if ($carModel) {
            //                throw new NotFoundException(['msg' => '该xx已被yy绑定，请解除绑定后继续操作']);
            //            }

            $model->nickname = $params['nickname'];
            $model->save();

            Db::commit();
            return retJson(Lang::PUTDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function deleteMedia()
    {

        $params      = self::getParam(['id']);
        (new MediaValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $model = MediaModel::where('id', $params['id'])->find();
            if (!$model) {
                throw new NotFoundException();
            }

            //            $otherModel = OtherModel::where('id', $params['id'])->find();
            //            if (!$otherModel) {
            //                throw new NotFoundException();
            //            }
            switch (config('filesystem.default')) {
                case 'local':
                    $path = config('filesystem.disks.local.root');
                    break;
                case 'public';
                    $path = config('filesystem.disks.public.root');
                    break;
                default:
                    $path = '';
            }
            unlink($path . DIRECTORY_SEPARATOR . $model->getData('savename'));

            $model->delete_time = NOW_TIME;
            $model->save();

            Db::commit();

            return retJson(Lang::DELETEDone);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }
}